<?php
/**
 * Created by PhpStorm.
 * User: shutao
 * Date: 2018/9/25
 * Time: 16:27
 */

namespace wechat\services;

use ttcommon\base\Date;
use ttext\backend\admin\library\DateService;
use ttext\backend\blog\models\ArticleContent;
use wechat\help\WeTextHelp;
use wechat\models\WeContent;
use wechat\models\WeKeyword;
use yii\base\UserException;

class WeKeywordService
{
    /**
     * 返回 指定主键 ID 的回复; (只适用于没有模板变量的内容)
     * @param integer $id 主键
     * @return string 已经 replace 过的内容
     * @throws UserException
     */
    public static function contentFromKeywordId($id)
    {
        if (!$record = WeKeyword::find()
            ->select(['c_type', 'c_id'])
            ->where(['id' => $id])->asArray()->one()) {
            throw new UserException('找不到指定的关键词记录');
        }
        return self::content($record['c_type'], $record['c_id']);
    }

    /**
     * 返回 指定公共号ID 的关键词回复 (只适用于没有模板变量的内容)；比如直接返回某个公众号的 subscribe 回复
     * @param string $wc_id 公众号 we.config.id
     * @param $keyword string 关键词，比如 subscribe
     * @return null|string
     * @throws \Exception
     */
    public static function contentFromKeyword($wc_id, $keyword)
    {
        if ($rows = WeKeyword::find()->where(['wc_id' => $wc_id, 'keyword' => $keyword, 'status' => WeKeyword::STATUS_ACTIVE])
            ->select(['start', 'end', 'c_type', 'c_id'])->asArray()->all()) {
            $activeAnswer = [];
            $currentDate = Date::currentYmd();
            foreach ($rows as $row) {
                if (DateService::isActiveDate($currentDate, $row['start'], $row['end'])) {
                    $activeAnswer = $row;
                    break;
                }
            }
            if ($activeAnswer) {
                return self::content($activeAnswer['c_type'], $activeAnswer['c_id']); // 回复内容类型，及其 ID
            }

        }
        return null;
    }

    /**
     * 处理关联词所绑定的具体内容
     * @param integer $keywordType 所绑定的类型，内容回复，或者文章
     * @param integer $contentId 所绑定的内容的 id
     * @return string 已经处理过的内容
     */
    private static function content($keywordType, $contentId)
    {
        if ($contentId) {
            switch ($keywordType) {
                case WeKeyword::C_TYPE_CONTENT:
                    if ($record = WeContent::find()->select(['type', 'content'])->where(['id' => $contentId])->asArray()->one()) {
                        return WeTextHelp::replaceSystemVar($record['content']);
                    }
                    break;
                case WeKeyword::C_TYPE_BLOG_ARTICLE: // 直接返回文章内容
                    if ($record = ArticleContent::find()->select(['content'])->where(['id' => $contentId])->asArray()->one()) {
                        return $record['content'];
                    }
                    break;
            }
        }
        return '';
    }
}